import { TestResultsProvider } from '@/contexts/TestResultsContext';
import { useColorScheme } from '@/hooks/useColorScheme';
import { ImmersiveProvider } from '@/utils/ImmersiveContext';
import { ModeProvider } from '@/utils/ModeContext';
import { getInfo } from '@/utils/api';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { DarkTheme, DefaultTheme, ThemeProvider } from '@react-navigation/native';
import { useFonts } from 'expo-font';
import { Stack, useRouter, useSegments } from 'expo-router';
import { StatusBar } from 'expo-status-bar';
import React, { createContext, useEffect, useState } from 'react';
import { PermissionsAndroid } from "react-native";
import 'react-native-reanimated';
import '../global.css';

export const AuthContext = createContext<{
    isLogin: boolean;
    setIsLogin: (v: boolean) => void;
}>({
    isLogin: false, setIsLogin: () => {
    }
});

export default function RootLayout() {
    const colorScheme = useColorScheme();
    const [loaded] = useFonts({
        SpaceMono: require('../assets/fonts/SpaceMono-Regular.ttf'),
    });
    const [isReady, setIsReady] = useState(false);
    const [isLogin, setIsLogin] = useState(false);
    const router = useRouter();
    const segments = useSegments();

    useEffect(() => {

        const checkLoginStatus = async () => {
            try {
                await PermissionsAndroid.requestMultiple([
                        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
                        PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,
                        PermissionsAndroid.PERMISSIONS.BLUETOOTH_ADVERTISE,
                        PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN,
                        PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT,
                        PermissionsAndroid.PERMISSIONS.CAMERA
                    ]
                )
                const token = await AsyncStorage.getItem('ACCESS_TOKEN');
                if (token) {
                    // 验证token是否有效
                    const info = await getInfo(token);
                    if (info?.code === 0) {
                        setIsLogin(true);
                    } else {
                        // token无效，清除存储
                        await AsyncStorage.multiRemove(['ACCESS_TOKEN', 'REFRESH_TOKEN', 'NICK_NAME', 'USER_NAME', 'USER', 'TEST_USER']);
                        setIsLogin(false);
                    }
                } else {
                    setIsLogin(false);
                }
            } catch (error) {
                console.error('检查登录状态失败:', error);
                // token验证失败，清除存储
                await AsyncStorage.multiRemove(['ACCESS_TOKEN', 'REFRESH_TOKEN', 'NICK_NAME', 'USER_NAME', 'USER', 'TEST_USER']);
                setIsLogin(false);
            } finally {
                setIsReady(true);
            }
        };

        checkLoginStatus();
    }, []);

    useEffect(() => {
        if (!isReady) return;
        if (!isLogin && segments[0] !== 'login') {
            router.replace('/login');
        }
        if (isLogin && segments[0] === 'login') {
            router.replace('/(tabs)');
        }
    }, [isReady, isLogin, segments]);

    if (!isReady) return null;

    if (!loaded) {
        // Async font loading only occurs in development.
        return null;
    }

    return (
        <AuthContext.Provider value={{isLogin, setIsLogin}}>
            <TestResultsProvider>
                <ModeProvider>
                    <ImmersiveProvider>
                        <ThemeProvider value={colorScheme === 'dark' ? DarkTheme : DefaultTheme}>
                            <Stack>
                                <Stack.Screen name="mode-selection" options={{headerShown: false}}/>
                                <Stack.Screen name="login" options={{headerShown: false}}/>
                                <Stack.Screen name="(tabs)" options={{headerShown: false}}/>
                                <Stack.Screen name="examination" options={{headerShown: false}}/>
                                <Stack.Screen name="examination-results" options={{headerShown: false}}/>
                                <Stack.Screen name="devices/SpO2" options={{headerShown: false}}/>
                                <Stack.Screen name="devices/Alcohol" options={{headerShown: false}}/>
                                <Stack.Screen name="devices/Dynamometer" options={{headerShown: false}}/>
                                <Stack.Screen name="devices/VitalCapacity" options={{headerShown: false}}/>
                                <Stack.Screen name="devices/Flicker" options={{headerShown: false}}/>
                                <Stack.Screen name="devices/Reaction" options={{headerShown: false}}/>
                                <Stack.Screen name="devices/Cardiovascular" options={{headerShown: false}}/>
                                <Stack.Screen name="+not-found"/>
                            </Stack>
                            <StatusBar style="auto"/>
                        </ThemeProvider>
                    </ImmersiveProvider>
                </ModeProvider>
            </TestResultsProvider>
        </AuthContext.Provider>
    );
}
